package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var rwMutex sync.RWMutex //创建读写锁
var value int

func readGo(index int) {
	for {
		rwMutex.RLock() //以读模式加锁,读数据的协程不产生阻塞,而写模式的进程阻塞
		num := value
		fmt.Printf("%dth 读goroutine，读出：%d\n", index, num)
		rwMutex.RUnlock() //以读模式解锁
	}
}

func writeGo(index int) {
	for {
		num := rand.Intn(1000) //生成随机数
		rwMutex.Lock()         //以写模式加锁,阻塞读模式的协程和其它写模式的协程
		value = num
		fmt.Printf("%dth 写goroutine，写入：%d\n", index, num)
		time.Sleep(time.Millisecond * 10) //放大实验现象
		rwMutex.Unlock()                  //以写模式解锁
	}
}

func main() {
	rand.Seed(time.Now().UnixNano()) //随机数种子

	for i := 0; i < 5; i++ {
		go readGo(i + 1)
	}

	for i := 0; i < 5; i++ {
		go writeGo(i + 1)
	}

	for {

	}
}
